package com.taldh.netty.io.socket.discard;

import com.taldh.netty.common.util.Logger;
import com.taldh.netty.io.NioDemoConfig;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class NioDiscardClient {

    static void startClient() throws IOException {
        // 1. 获取通道
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress(
                NioDemoConfig.SOCKET_SERVER_IP, NioDemoConfig.SOCKET_SERVER_PORT
        ));

        // 2. 切换成非阻塞模式
        socketChannel.configureBlocking(false);

        // 不断自旋，等待连接完成，或者一些其它的事情
        while (!socketChannel.finishConnect()) {
            Logger.debug("连接中...");
        }

        Logger.info("客户端启动成功");
        // 3. 指定分配大小的缓存区
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        byteBuffer.put("hello world".getBytes());
        byteBuffer.flip();

        // 4. 发送到服务器
        socketChannel.write(byteBuffer);
        socketChannel.shutdownOutput();
        socketChannel.close();
    }

    public static void main(String[] args) throws IOException {
        startClient();
    }

}
